#include "BoardLogger.h"

#include <QFileInfo>

BoardLogger* BoardLogger::m_instance = nullptr;

BoardLogger& BoardLogger::instance()
{
    static QMutex mutex;
    QMutexLocker locker(&mutex);

    if (m_instance == nullptr) {
        m_instance = new BoardLogger();
    }
    return *m_instance;
}

void BoardLogger::logSerialData(const QString& portName, const QByteArray& data, bool isReceived)
{
    QString direction = isReceived ? "RX" : "TX";
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
    QString logContent = QString("[%1] %2 [%3]: %4")
                             .arg(timestamp)
                             .arg(portName)
                             .arg(direction)
                             .arg(QString::fromUtf8(data));

    writeToLog(logContent);
}

void BoardLogger::logMessage(const QString& message)
{
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
    QString logContent = QString("[%1] %2").arg(timestamp).arg(message);

    writeToLog(logContent);
}

void BoardLogger::logHexData(const QString& portName, const QByteArray& data, bool isReceived)
{
    QString direction = isReceived ? "RX" : "TX";
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
    QString hexString = data.toHex(' ').toUpper();
    QString logContent =
        QString("[%1] %2 [%3] HEX: %4").arg(timestamp).arg(portName).arg(direction).arg(hexString);

    writeToLog(logContent);
}

void BoardLogger::writeToLog(const QString& logContent)
{
    QMutexLocker locker(&m_mutex);

    QString logPath = getCurrentLogPath();

    // 如果日期变化了，更新当前日志路径
    if (m_currentLogPath != logPath) {
        ensureLogDirectory(logPath);
        m_currentLogPath = logPath;
    }

    QFile logFile(logPath);
    if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream stream(&logFile);
        stream << logContent;
        // 添加换行符
        if (!logContent.endsWith('\n')) {
            stream << '\n';
        }
        logFile.close();
    }
}

QString BoardLogger::getCurrentLogPath()
{
    QDate currentDate = QDate::currentDate();
    QString yearMonth = currentDate.toString("yyyy-MM");
    QString day = currentDate.toString("dd");
    return QString("log/%1/%2/board.log").arg(yearMonth).arg(day);
}

void BoardLogger::ensureLogDirectory(const QString& logPath)
{
    QFileInfo fileInfo(logPath);
    QDir logDir = fileInfo.absoluteDir();
    if (!logDir.exists()) {
        logDir.mkpath(".");
    }
}